<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column' }">
      <!-- <PatientList @select="onSelectPatient" /> -->
      <PatientListDrawer :patient-list="patientList" :selected-item="selectedItem" @select="selectPatient" @refresh="getInpRecordList" />
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="selectedItem">
        <template #prefix>
          <div class="text-2xl pr-4 text-primary font-semibold">{{ selectedItem.bedCode }}床</div>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="住院科室" :width="200" :value="selectedItem.ksmc" />
            <LabelValue label="住院号" :width="220" :value="selectedItem.admissionCode" />
            <!-- <LabelValue label="过敏史" :width="200" :value="selectedItem.brGms" /> -->
            <AllergyHistory :width="200" :value="selectedItem.brGms" :patient-info="selectedItem" @success="(e) => (selectedItem.brGms = e)" />
            <LabelValue label="保险信息" :width="200" :value="selectedItem.bxxx" />
            <LabelValue label="住院天数" :width="160" :value="selectedItem.zyts" />
          </div>
          <div class="flex items-center">
            <LabelValue label="住院病区" :width="200" :value="selectedItem.wardName" />
            <LabelValue label="入区时间" :width="220" :value="selectedItem.lastDeptRegTime" />
            <LabelValue label="账户余额" :width="200" :value="formatAmount(selectedItem.yjje) + '元'" />
            <LabelValue label="入院诊断" :width="160" :value="selectedItem.ryzd" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-hidden" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <div class="flex justify-between mt-2">
            <div>
              <a-radio-group v-model:value="tabsKey" button-style="solid" @change="onChangeTab">
                <a-radio-button :value="1">类别费用</a-radio-button>
                <a-radio-button :value="2">明细</a-radio-button>
              </a-radio-group>
              <a-radio-group v-if="tabsKey === 2" v-model:value="statusKey" class="ml-4" @change="onChangeStatus">
                <a-radio :value="3">全部</a-radio>
                <a-radio :value="0">临时</a-radio>
                <a-radio :value="1">长期</a-radio>
              </a-radio-group>
            </div>
            <a-space v-if="tabsKey === 2">
              <a-button v-if="allAuditFlag" :disabled="allAuditDisabled !== 0" type="primary" @click="allAuditStatus(2, 3)">全部审核</a-button>
              <BaseButton v-else danger confirm-text="确认全部撤销审核?" type="primary" @click="allAuditStatus(3, 2)"> 全部撤审 </BaseButton>
            </a-space>
          </div>
          <div v-if="tabsKey === 1" class="w-500">
            <BaseTable class="mt-2" :loading="loading" column-code="000109" extra-height="800" :data-source="dataCategory" fill bordered>
              <template #bodyCell="{ column, index }">
                <template v-if="column.dataIndex === 'xh'">
                  {{ index + 1 }}
                </template>
              </template>
              <template v-if="tabsKey === 1" #summary>
                <a-table-summary fixed>
                  <a-table-summary-row>
                    <a-table-summary-cell>-</a-table-summary-cell>
                    <a-table-summary-cell class="text-right">
                      <a-typography-text>合计</a-typography-text>
                    </a-table-summary-cell>
                    <a-table-summary-cell class="text-right">
                      <a-typography-text>{{ dataTotal ? dataTotal.toFixed(2) : '' }}</a-typography-text>
                    </a-table-summary-cell>
                  </a-table-summary-row>
                </a-table-summary>
              </template>
            </BaseTable>
          </div>
          <div v-else>
            <!-- 临时&全部 -->
            <div v-if="statusKey === 0 || statusKey === 3">
              <BaseTable class="mt-2" :loading="loading" :column-code="columnCodeL" :scroll="{ x: 1900 }" extra-height="0" :data-source="dataSource" fill>
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.dataIndex === 'xh'">
                    {{ index + 1 }}
                  </template>
                  <template v-if="column.dataIndex === 'adv'">
                    <DoctorAdviceOrder
                      :row-data="record"
                      :params-key="{ mc: 'advName', sl: 'clinicalDose', dw: 'clinicalDoseUnit', gg: 'spc', yf: 'fyff', pl: 'pl' }"
                    />
                  </template>
                  <template v-if="column.dataIndex === 'status'">
                    <a-tag v-if="record.status === 2" color="blue">未审核</a-tag>
                    <a-tag v-else-if="record.status === 3" color="green">已审核</a-tag>
                    <span v-else>-</span>
                  </template>
                  <template v-if="column.dataIndex === 'action'">
                    <!-- chargeStatus 0:未结账|1：已结账 |2：退费中 -->
                    <a-button
                      v-if="record.chargeStatus === 0 || record.chargeStatus === 2"
                      :disabled="record.status === 3"
                      type="link"
                      size="small"
                      @click=";(rowData = record), (open = true)"
                      >撤销费用</a-button
                    >
                    <a-button
                      v-if="record.status === 2"
                      :disabled="record.chargeStatus !== 0"
                      type="link"
                      size="small"
                      @click="changeAuditStatus([record.id], 3)"
                      >审核</a-button
                    >
                    <BaseButton
                      v-if="record.status === 3"
                      danger
                      confirm-text="确认撤销审核?"
                      type="link"
                      size="small"
                      @click="changeAuditStatus([record.id], 2)"
                    >
                      撤销审核
                    </BaseButton>
                  </template>
                </template>
              </BaseTable>
            </div>
            <!-- 长期 -->
            <div v-else class="flex justify-between">
              <div class="w-7/12">
                <BaseTable
                  class="mt-2"
                  :loading="loading1"
                  column-code="000341"
                  :custom-row="(record) => ({ onClick: () => onSelectRow(record) })"
                  :row-class-name="(record) => (record.parentId === selectLeftRow.parentId ? 'selected-row' : '')"
                  extra-height="100"
                  :data-source="tableData"
                  :pagination="pagination"
                >
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'adv'">
                      <DoctorAdviceOrder
                        :row-data="record"
                        :params-key="{ mc: 'adv.mc', gg: 'adv.gg', sl: 'clinicalDose', dw: 'clinicalDoseUnit', yf: 'deliverRoute.fyff', pl: 'fqy.pl' }"
                      />
                    </template>
                  </template>
                </BaseTable>
              </div>
              <a-divider type="vertical" class="h-full" />
              <div class="w-5/12">
                <BaseTable class="mt-2" :loading="loading2" :column-code="columnCodeR" extra-height="0" :data-source="rightData" fill :pagination="pagination1">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'status'">
                      <a-tag v-if="record.status === 2" color="blue">未审核</a-tag>
                      <a-tag v-else-if="record.status === 3" color="green">已审核</a-tag>
                      <span v-else>-</span>
                    </template>
                    <template v-if="column.dataIndex === 'action'">
                      <a-button
                        v-if="record.chargeStatus === 0 || record.chargeStatus === 2"
                        type="link"
                        size="small"
                        @click=";(rowData = record), (open = true)"
                        >撤销费用</a-button
                      >
                      <a-button
                        v-if="record.status === 2 && (record.chargeStatus === 0 || record.chargeStatus === 2)"
                        type="link"
                        size="small"
                        @click="changeAuditStatus([record.id], 3)"
                        >审核</a-button
                      >
                      <BaseButton
                        v-if="record.status === 3"
                        danger
                        confirm-text="确认撤销审核?"
                        type="link"
                        size="small"
                        @click="changeAuditStatus([record.id], 2)"
                      >
                        撤销审核
                      </BaseButton>
                    </template>
                  </template>
                </BaseTable>
              </div>
            </div>
          </div>
        </a-card>
      </div>
    </div>
    <Edit v-model:open="open" :row-data="rowData" @success="getData" />
  </div>
</template>

<script setup>
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import PatientListDrawer from '@/components/business/PatientListDrawer'
import LabelValue from '@/components/LabelValue'
import { formatAmount } from '@/utils/format'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import Edit from './Edit'

const columnCodeL = ref('000110')
const columnCodeR = ref('000342')
const loading = ref(false)
const dataSource = ref([])
const dataCategory = ref([])
const selectLeftRow = ref({})
const tabsKey = ref(1)
const statusKey = ref(3)
const patientList = ref([])
const selectedItem = ref({})
const open = ref(false)
const rowData = ref(false)
const dataTotal = ref(0)
const allAuditFlag = ref(true)

//获取左侧列表数据
const getInpRecordList = async () => {
  const { code, data, msg } = await post('/inp/inpComprehensive/getInpRecordInfo')
  if (code !== 0) return message.error(msg)
  patientList.value = data
  if (data && data.length > 0) {
    selectedItem.value = data[0]
    getData()
  }
}
//选中的数据
const selectPatient = (patient) => {
  selectedItem.value = patient
  getData()
}
const allAuditDisabled = ref(0)
//获取数据
const getData = async () => {
  loading.value = true
  //类别费用
  const res = await post('/inp/inpComprehensive/getPatientBillList', {
    inplsh: selectedItem.value.inplsh,
    advExecType: tabsKey.value === 2 && statusKey.value === 0 ? '0' : undefined,
    statusList: [2, 3]
  })
  loading.value = false
  if (res.code !== 0) return message.error(res.msg || '获取数据失败')
  dataSource.value = res.data.patientBillList || []
  allAuditDisabled.value = res.data.chargeStatus
  dataSource.value = dataSource.value.map((it) => {
    return { ...it, advOrderType: 0 }
  })
  dataCategory.value = res.data.patientBillTypeList
  dataTotal.value = res.data.amount
  const flag = dataSource.value.filter((it) => {
    return it.status === 2
  })
  if (flag.length > 0 || dataSource.value.length === 0) {
    allAuditFlag.value = true
  } else {
    allAuditFlag.value = false
  }
}
const {
  loading: loading1,
  tableData,
  getData: getLongData,
  pagination
} = useTable({
  url: '/inp/clinicalOrder/getClinicalOrderAllList',
  immediate: false,
  formatParams: () => {
    return {
      inplsh: selectedItem.value.inplsh,
      type: '2',
      inpAdvice: '1'
    }
  }
})
const {
  loading: loading2,
  tableData: rightData,
  getData: getRightData,
  pagination: pagination1
} = useTable({
  url: '/inp/inpComprehensive/getlnpExpensesList',
  immediate: false,
  formatParams: () => {
    return {
      statusList: ['2', '3'],
      // advCode: selectLeftRow.value.advCode,
      inplsh: selectedItem.value.inplsh,
      inpAdviceid: selectLeftRow.value.inpAdviceid,
      advExecType: 1
    }
  },
  onSuccess: () => {
    const flag = rightData.value.filter((it) => {
      return it.status === 2
    })
    if (flag.length > 0 || rightData.value.length === 0) {
      allAuditFlag.value = true
    } else {
      allAuditFlag.value = false
    }
  }
})
const onChangeStatus = (e) => {
  statusKey.value === 3
  if (e.target.value === 1) {
    getLongData()
  } else {
    getData()
  }
}
const allAuditStatus = (status, type) => {
  const ids = []
  if (statusKey.value === 0 || statusKey.value === 3) {
    if (dataSource.value.length <= 0) return message.error('暂无数据')
    dataSource.value.forEach((item) => {
      if (item.status === status) ids.push(item.id)
    })
  } else {
    if (rightData.value.length <= 0) return message.error('暂无数据')
    rightData.value.forEach((item) => {
      if (item.status === status) ids.push(item.id)
    })
  }
  changeAuditStatus(ids, type)
}
const changeAuditStatus = async (ids, status) => {
  const res = await post('/inp/inpComprehensive/doUpdatelnpExpensesStatus', {
    ids: ids,
    status: status,
    inplsh: selectedItem.value.inplsh
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  if (statusKey.value === 0 || statusKey.value === 3) {
    getData()
  } else {
    getRightData()
  }
}
const onChangeTab = () => {
  getData()
}
const onSelectRow = (select) => {
  selectLeftRow.value = select
  getRightData()
}
onMounted(() => {
  getInpRecordList()
  if (getSystemConfig('INP_CHARGE_ENTER_ACCOUNT_MODE') === '0') {
    //住院费用依据
    columnCodeL.value = '000110'
    columnCodeR.value = '000342'
  } else {
    columnCodeL.value = '000343'
    columnCodeR.value = '000344'
  }
})
</script>
<style lang="less" scoped>
.w-500 {
  width: 500px;
}
.bg-color {
  background: var(--thin-color);
}
:deep(.ant-table-row-expand-icon) {
  display: none;
}
.classify-checkall {
  .ant-tag {
    font-size: 14px;
    line-height: 30px;
    padding-inline: 14px;
  }
}
</style>
